<script lang="ts" setup>
import { 
  computed, ref,
  // defineEmits,  watchEffect, unref 
} from 'vue'
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import hljs from 'highlight.js'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { t } from '@/locales'

interface Props {
  inversion?: boolean
  error?: boolean
  text?: string
  loading?: boolean
  isNew: boolean
}

const props = defineProps<Props>()

const { isMobile } = useBasicLayout()

const textRef = ref<HTMLElement>()

// const emit = defineEmits(['on-msg-showed']);

const mdi = new MarkdownIt({
  linkify: true,
  highlight(code, language) {
    const validLang = !!(language && hljs.getLanguage(language))
    if (validLang) {
      const lang = language ?? ''
      return highlightBlock(hljs.highlight(lang, code, true).value, lang)
    }
    return highlightBlock(hljs.highlightAuto(code).value, '')
  },
})

mdi.use(mdKatex, { blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000' })

const wrapClass = computed(() => {
  return [
    'text-wrap',
    'min-w-[20px]',
    'rounded-md',
    isMobile.value ? 'p-2' : 'px-3 py-2',
    props.inversion ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]',
    props.inversion ? 'dark:bg-[#a1dc95]' : 'dark:bg-[#1e1e20]',
    { 'text-red-500': props.error },
  ]
})

const isPicURL = (text : string) => {
  return /^http(s?):\/\/.*\.png$/ig.test(text);
}

const text = computed(() => {
  const value = props.text ?? ''
  if(!props.inversion) {
    if(isPicURL(value)) {
      return `<a class="img-in-chat" href="${value}" target="_blank"><img src="${value}"></a>`
    }else {
      return mdi.render(value)
      // return mdi.render(unref(showText))
    }
  }else {
    return value;
  }
})

// const showText = ref('');

// function typewriter(text: string, i: number = 0) {
//   const PER_COUNT = 10;
//   setTimeout(() => {
//     showText.value += text.substring(i, i + PER_COUNT);
//     if(i < text.length - 1) {
//       typewriter(text, i + PER_COUNT);
//     }else {
//       emit('on-msg-showed');
//     }
//   }, 50);
// }

// watchEffect(() => {
//   if(props.isNew) {
//     showText.value = '';
//     typewriter(props.text as string)
//   }else {
//     showText.value = props.text as string;
//   }
// })

function highlightBlock(str: string, lang?: string) {
  return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">${t('chat.copyCode')}</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`
}

defineExpose({ textRef })
</script>

<template>
  <div class="text-black" :class="wrapClass">
    <template v-if="loading">
      <span class="flex items-center dark:text-white h-[20px] block">{{ $t('chat.thinking') }}...<span class="dark:text-white w-[2px] ml-1 inline-block h-[15px] animate-blink"/></span>
    </template>
    <template v-else>
      <div ref="textRef" class="leading-relaxed break-words">
        <div v-if="!inversion" class="markdown-body" v-html="text" />
        <div v-else class="whitespace-pre-wrap" v-text="text" />
      </div>
    </template>
  </div>
</template>

<style lang="less">
@import url(./style.less);
</style>

<style lang="less" scoped>
:deep(.img-in-chat){
  text-decoration: none;
  outline: none;
  >img{
    border: none;
    outline: none;
    width: 200px;
  }
}
</style>